// UI管理器类
class UIManager {
    constructor() {
        this.currentScreen = 'start';
        this.upgradeOptions = [];
        this.selectedUpgrade = null;
        
        this.setupEventListeners();
    }
    
    // 设置事件监听器
    setupEventListeners() {
        // 开始按钮
        const startButton = document.getElementById('startButton');
        if (startButton) {
            startButton.addEventListener('click', () => {
                this.startGame();
            });
        }
        
        // 重新开始按钮
        const restartButton = document.getElementById('restartButton');
        if (restartButton) {
            restartButton.addEventListener('click', () => {
                this.restartGame();
            });
        }
    }
    
    // 显示屏幕
    showScreen(screenName) {
        this.hideAllScreens();
        
        switch(screenName) {
            case 'start':
                document.getElementById('startScreen').classList.remove('hidden');
                break;
            case 'game':
                document.getElementById('gameUI').classList.remove('hidden');
                break;
            case 'upgrade':
                document.getElementById('upgradeScreen').classList.remove('hidden');
                break;
            case 'gameOver':
                document.getElementById('gameOverScreen').classList.remove('hidden');
                break;
        }
        
        this.currentScreen = screenName;
    }
    
    // 隐藏所有屏幕
    hideAllScreens() {
        const screens = ['startScreen', 'gameUI', 'upgradeScreen', 'gameOverScreen'];
        screens.forEach(screenId => {
            const element = document.getElementById(screenId);
            if (element) {
                element.classList.add('hidden');
            }
        });
    }
    
    // 开始游戏
    startGame() {
        this.showScreen('game');
        if (window.game) {
            window.game.start();
        }
    }
    
    // 重新开始游戏
    restartGame() {
        this.showScreen('start');
        if (window.game) {
            window.game.reset();
        }
    }
    
    // 更新游戏UI
    updateGameUI(player, gameTime) {
        // 更新生命值条
        const healthFill = document.getElementById('healthFill');
        if (healthFill) {
            const healthPercentage = player.getHealthPercentage();
            healthFill.style.width = `${healthPercentage * 100}%`;
        }
        
        // 更新等级信息
        const levelElement = document.getElementById('level');
        const experienceElement = document.getElementById('experience');
        if (levelElement && experienceElement) {
            levelElement.textContent = `等级: ${player.level}`;
            const experienceProgress = player.getExperienceProgress();
            const experienceToNext = player.experienceToNextLevel || getCumulativeExperienceForLevel(player.level + 1);
            experienceElement.textContent = `经验: ${player.experience}/${experienceToNext}`;
        }
        
        // 更新时间
        const timerElement = document.getElementById('timer');
        if (timerElement) {
            timerElement.textContent = `时间: ${Utils.formatTime(gameTime)}`;
        }
    }
    
    // 显示升级界面
    showUpgradeScreen(upgradeOptions) {
        this.upgradeOptions = upgradeOptions;
        this.selectedUpgrade = null;
        this.upgradeTimer = 0;
        this.upgradeTimeLimit = BALANCE_CONFIG.UPGRADE_SELECTION_TIME;
        
        const upgradeContainer = document.getElementById('upgradeOptions');
        if (upgradeContainer) {
            upgradeContainer.innerHTML = '';
            
            // 添加倒计时显示
            const timerElement = document.createElement('div');
            timerElement.id = 'upgradeTimer';
            timerElement.className = 'upgrade-timer';
            timerElement.innerHTML = `
                <div class="timer-bar">
                    <div class="timer-fill"></div>
                </div>
                <div class="timer-text">选择时间: <span id="timerSeconds">1.0</span>秒</div>
            `;
            upgradeContainer.appendChild(timerElement);
            
            upgradeOptions.forEach((option, index) => {
                const optionElement = this.createUpgradeOption(option, index);
                upgradeContainer.appendChild(optionElement);
            });
        }
        
        this.showScreen('upgrade');
        
        // 开始倒计时
        this.startUpgradeTimer();
    }
    
    // 创建升级选项元素
    createUpgradeOption(option, index) {
        const div = document.createElement('div');
        div.className = 'upgrade-option';
        div.dataset.index = index;
        
        div.innerHTML = `
            <h3>${option.name}</h3>
            <p>${option.description}</p>
            <p><strong>${option.effect}</strong></p>
        `;
        
        div.addEventListener('click', () => {
            this.selectUpgrade(index);
        });
        
        div.addEventListener('mouseenter', () => {
            this.selectedUpgrade = index;
            this.updateUpgradeSelection();
        });
        
        return div;
    }
    
    // 选择升级
    selectUpgrade(index) {
        this.selectedUpgrade = index;
        
        // 播放按钮点击音效
        if (window.game && window.game.sounds && window.game.sounds.buttonClick) {
            window.game.soundGenerator.playSound(window.game.sounds.buttonClick);
        }
        
        // 清除定时器，立即应用升级
        if (this.upgradeTimerInterval) {
            clearInterval(this.upgradeTimerInterval);
            this.upgradeTimerInterval = null;
        }
        
        this.applyUpgrade();
    }
    
    // 更新升级选择状态
    updateUpgradeSelection() {
        const options = document.querySelectorAll('.upgrade-option');
        options.forEach((option, index) => {
            if (index === this.selectedUpgrade) {
                option.style.background = 'rgba(74, 144, 226, 0.6)';
                option.style.transform = 'scale(1.05)';
            } else {
                option.style.background = 'rgba(74, 144, 226, 0.2)';
                option.style.transform = 'scale(1)';
            }
        });
    }
    
    // 开始升级倒计时
    startUpgradeTimer() {
        this.upgradeTimer = 0;
        this.updateUpgradeTimer();
        
        // 清除之前的定时器
        if (this.upgradeTimerInterval) {
            clearInterval(this.upgradeTimerInterval);
        }
        
        // 设置定时器，每10ms更新一次
        this.upgradeTimerInterval = setInterval(() => {
            this.upgradeTimer += 10;
            this.updateUpgradeTimer();
            
            if (this.upgradeTimer >= this.upgradeTimeLimit) {
                this.autoSelectUpgrade();
            }
        }, 10);
    }
    
    // 更新升级倒计时显示
    updateUpgradeTimer() {
        const remainingTime = this.upgradeTimeLimit - this.upgradeTimer;
        const remainingSeconds = (remainingTime / 1000).toFixed(1);
        
        // 更新倒计时文本
        const timerSecondsElement = document.getElementById('timerSeconds');
        if (timerSecondsElement) {
            timerSecondsElement.textContent = remainingSeconds;
        }
        
        // 更新进度条
        const timerFillElement = document.querySelector('.timer-fill');
        if (timerFillElement) {
            const progress = remainingTime / this.upgradeTimeLimit;
            timerFillElement.style.width = `${progress * 100}%`;
            
            // 根据剩余时间改变颜色
            if (progress > 0.5) {
                timerFillElement.style.backgroundColor = '#4CAF50'; // 绿色
            } else if (progress > 0.2) {
                timerFillElement.style.backgroundColor = '#FF9800'; // 橙色
            } else {
                timerFillElement.style.backgroundColor = '#F44336'; // 红色
            }
        }
    }
    
    // 自动选择升级
    autoSelectUpgrade() {
        // 清除定时器
        if (this.upgradeTimerInterval) {
            clearInterval(this.upgradeTimerInterval);
            this.upgradeTimerInterval = null;
        }
        
        // 如果没有选择，随机选择一个
        if (this.selectedUpgrade === null) {
            this.selectedUpgrade = Math.floor(Math.random() * this.upgradeOptions.length);
            console.log('自动选择升级:', this.upgradeOptions[this.selectedUpgrade]);
        }
        
        // 应用升级
        this.applyUpgrade();
    }
    
    // 应用升级
    applyUpgrade() {
        // 清除定时器
        if (this.upgradeTimerInterval) {
            clearInterval(this.upgradeTimerInterval);
            this.upgradeTimerInterval = null;
        }
        
        if (this.selectedUpgrade !== null && this.upgradeOptions[this.selectedUpgrade]) {
            const option = this.upgradeOptions[this.selectedUpgrade];
            
            // 播放升级音效
            if (window.game && window.game.sounds && window.game.sounds.upgrade) {
                window.game.soundGenerator.playSound(window.game.sounds.upgrade);
            }
            
            console.log('应用升级:', option);
            
            if (window.game && window.game.weaponManager) {
                if (option.type === 'upgrade' || option.type === 'new') {
                    window.game.weaponManager.upgradeWeapon(option.weaponType);
                    console.log('武器升级完成，当前武器数量:', window.game.weaponManager.weapons.length);
                } else if (option.type === 'player_upgrade') {
                    window.game.applyPlayerUpgrade(option.upgradeType);
                    console.log('玩家属性升级完成:', option.upgradeType);
                }
            }
            
            // 返回游戏
            this.showScreen('game');
            if (window.game) {
                // 确保游戏状态正确恢复
                window.game.state = GAME_STATES.PLAYING;
                window.game.isPaused = false;
                console.log('游戏状态恢复:', window.game.state, window.game.isPaused);
                window.game.resume();
            }
        }
    }
    
    // 显示游戏结束界面
    showGameOverScreen(survivalTime) {
        const finalScoreElement = document.getElementById('finalScore');
        if (finalScoreElement) {
            finalScoreElement.textContent = `生存时间: ${Utils.formatTime(survivalTime)}`;
        }
        
        this.showScreen('gameOver');
    }
    
    // 显示消息
    showMessage(message, duration = 3000) {
        // 创建消息元素
        const messageElement = document.createElement('div');
        messageElement.className = 'game-message';
        messageElement.textContent = message;
        messageElement.style.cssText = `
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 20px;
            border-radius: 10px;
            font-size: 1.2em;
            z-index: 1000;
            animation: fadeInOut ${duration}ms ease-in-out;
        `;
        
        // 添加动画样式
        const style = document.createElement('style');
        style.textContent = `
            @keyframes fadeInOut {
                0% { opacity: 0; transform: translate(-50%, -50%) scale(0.8); }
                20% { opacity: 1; transform: translate(-50%, -50%) scale(1); }
                80% { opacity: 1; transform: translate(-50%, -50%) scale(1); }
                100% { opacity: 0; transform: translate(-50%, -50%) scale(0.8); }
            }
        `;
        document.head.appendChild(style);
        
        document.body.appendChild(messageElement);
        
        // 自动移除消息
        setTimeout(() => {
            if (messageElement.parentNode) {
                messageElement.parentNode.removeChild(messageElement);
            }
        }, duration);
    }
    
    // 显示伤害数字
    showDamageNumber(x, y, damage, color = '#ff0000') {
        const damageElement = document.createElement('div');
        damageElement.textContent = damage.toString();
        damageElement.style.cssText = `
            position: absolute;
            left: ${x}px;
            top: ${y}px;
            color: ${color};
            font-size: 1.2em;
            font-weight: bold;
            pointer-events: none;
            z-index: 1000;
            animation: damageFloat 1s ease-out forwards;
        `;
        
        // 添加动画样式
        const style = document.createElement('style');
        style.textContent = `
            @keyframes damageFloat {
                0% { opacity: 1; transform: translateY(0); }
                100% { opacity: 0; transform: translateY(-50px); }
            }
        `;
        document.head.appendChild(style);
        
        document.body.appendChild(damageElement);
        
        // 自动移除
        setTimeout(() => {
            if (damageElement.parentNode) {
                damageElement.parentNode.removeChild(damageElement);
            }
        }, 1000);
    }
    
    // 显示经验获得
    showExperienceGain(x, y, amount) {
        const expElement = document.createElement('div');
        expElement.textContent = `+${amount} XP`;
        expElement.style.cssText = `
            position: absolute;
            left: ${x}px;
            top: ${y}px;
            color: #FFD700;
            font-size: 1em;
            font-weight: bold;
            pointer-events: none;
            z-index: 1000;
            animation: expFloat 1.5s ease-out forwards;
        `;
        
        // 添加动画样式
        const style = document.createElement('style');
        style.textContent = `
            @keyframes expFloat {
                0% { opacity: 1; transform: translateY(0) scale(1); }
                50% { opacity: 1; transform: translateY(-30px) scale(1.2); }
                100% { opacity: 0; transform: translateY(-60px) scale(0.8); }
            }
        `;
        document.head.appendChild(style);
        
        document.body.appendChild(expElement);
        
        // 自动移除
        setTimeout(() => {
            if (expElement.parentNode) {
                expElement.parentNode.removeChild(expElement);
            }
        }, 1500);
    }
    
    // 显示等级提升
    showLevelUp() {
        this.showMessage('等级提升！', 2000);
    }
    
    // 显示游戏暂停
    showPause() {
        this.showMessage('游戏暂停', 1000);
    }
    
    // 显示游戏恢复
    showResume() {
        this.showMessage('游戏继续', 1000);
    }
    
    // 重置UI
    reset() {
        this.currentScreen = 'start';
        this.upgradeOptions = [];
        this.selectedUpgrade = null;
        this.showScreen('start');
    }
}

// 创建全局UI管理器实例
const uiManager = new UIManager(); 

class UI {
    constructor(game) {
        this.game = game;
    }
    
    // 渲染游戏UI
    render() {
        if (this.game.state === GAME_STATES.PLAYING) {
            this.renderGameUI();
        } else if (this.game.state === GAME_STATES.UPGRADING) {
            this.renderUpgrade();
        }
    }
    
    // 渲染游戏UI
    renderGameUI() {
        const ctx = this.game.ctx;
        const player = this.game.player;
        const gameTime = this.game.gameTime;
        
        // 渲染生命值条
        const healthBarWidth = 200;
        const healthBarHeight = 20;
        const healthBarX = 10;
        const healthBarY = 10;
        const healthPercentage = player.getHealthPercentage();
        
        ctx.fillStyle = '#333333';
        ctx.fillRect(healthBarX, healthBarY, healthBarWidth, healthBarHeight);
        
        ctx.fillStyle = '#FF0000';
        ctx.fillRect(healthBarX, healthBarY, healthBarWidth * healthPercentage, healthBarHeight);
        
        // 渲染等级信息
        ctx.fillStyle = '#FFFFFF';
        ctx.font = '24px Arial';
        ctx.textAlign = 'left';
        ctx.fillText(`等级: ${player.level}`, 10, 50);
        
        const experienceProgress = player.getExperienceProgress();
        const experienceToNext = player.experienceToNextLevel || getCumulativeExperienceForLevel(player.level + 1);
        ctx.fillText(`经验: ${player.experience}/${experienceToNext}`, 10, 80);
        
        // 渲染时间
        ctx.fillText(`时间: ${Utils.formatTime(gameTime)}`, 10, 110);
    }
    
    // 渲染升级界面
    renderUpgrade() {
        if (this.game.state !== GAME_STATES.UPGRADING) return;
        
        const ctx = this.game.ctx;
        const options = this.game.upgradeOptions;
        const selectedOption = this.game.selectedUpgrade;
        
        // 渲染背景
        ctx.fillStyle = 'rgba(0, 0, 0, 0.8)';
        ctx.fillRect(0, 0, this.game.canvas.width, this.game.canvas.height);
        
        // 渲染选项
        options.forEach((option, index) => {
            const optionX = 10;
            const optionY = 10 + index * 100;
            const optionWidth = this.game.canvas.width - 20;
            const optionHeight = 90;
            
            ctx.fillStyle = selectedOption === index ? 'rgba(74, 144, 226, 0.6)' : 'rgba(74, 144, 226, 0.2)';
            ctx.fillRect(optionX, optionY, optionWidth, optionHeight);
            
            ctx.fillStyle = '#FFFFFF';
            ctx.font = '24px Arial';
            ctx.textAlign = 'left';
            ctx.fillText(option.name, optionX + 10, optionY + 30);
            ctx.fillText(option.description, optionX + 10, optionY + 60);
            ctx.fillText(option.effect, optionX + 10, optionY + 90);
        });
        
        // 渲染倒计时
        const timeLeft = Math.ceil(this.game.upgradeSelectionTimer / 1000);
        const progress = this.game.upgradeSelectionTimer / this.game.maxUpgradeSelectionTime;
        
        ctx.fillStyle = '#FFFFFF';
        ctx.font = '24px Arial';
        ctx.textAlign = 'center';
        ctx.fillText(`剩余时间: ${timeLeft}`, this.game.canvas.width / 2, 100);
        
        // 渲染进度条背景
        const barWidth = 300;
        const barHeight = 20;
        const barX = (this.game.canvas.width - barWidth) / 2;
        const barY = 120;
        
        ctx.fillStyle = '#333333';
        ctx.fillRect(barX, barY, barWidth, barHeight);
        
        // 渲染进度条
        let barColor = '#4CAF50'; // 绿色
        if (progress < 0.3) {
            barColor = '#F44336'; // 红色
        } else if (progress < 0.6) {
            barColor = '#FF9800'; // 橙色
        }
        
        ctx.fillStyle = barColor;
        ctx.fillRect(barX, barY, barWidth * progress, barHeight);
    }
}

function displayExperience(player) {
    const currentExp = player.experience || 0;
    const nextLevelExp = player.experienceToNextLevel || getCumulativeExperienceForLevel(player.level + 1);

    // 容错处理，确保 nextLevelExp 不为 undefined
    const formattedNextLevelExp = nextLevelExp !== undefined ? nextLevelExp : 'MAX';

    document.getElementById('experience').textContent = `经验: ${currentExp}/${formattedNextLevelExp}`;
}
